from urllib import response

from flask import request, jsonify, session, redirect, url_for, make_response
from models.index import User
from models import db
from . import passport_blu


@passport_blu.route("/passport/login", methods=["GET", "POST"])
def login():
    username = request.json.get('username')  # 获取表单中输入的用户名和密码
    password = request.json.get('password')

    # print(username, password)
    user = db.session.query(User).filter(User.nick_name == username, User.password_hash == password).first()
    if user:
        ret = {
            "errno": 0,
            "errmsg": "登录成功"
        }
        # print("--------------------1------------")
        session['user_id'] = user.user_id
        session['nick_name'] = username
        # print("----------------", username)
    else:
        ret = {
            "errno": 2001,
            "errmsg": "用户名或密码错误"
        }
    return jsonify(ret)


@passport_blu.route("/passport/logout")
def logout():
    # 清空登录状态
    session.clear()

    return redirect(url_for("index_blu.index"))


@passport_blu.route("/passport/signup", methods=["GET", "POST"])
def signup():
    username = request.json.get("username")
    password = request.json.get("password")
    address = request.json.get("address")
    phone = request.json.get("phone")
    code = request.json.get("code")
    # 测试数据
    print(username, password, address, phone, image_code)
    # 创建新用户
    # 查询是不是又相同的用户
    if db.session.query(User).filter(User.nick_name == username, User.password_hash == password).first():
        return jsonify({
            "errno": 1001,
            "errmsg": "已经注册"
        })

    # 注册用户
    # 将新用户的数据插入到数据库
    user = User()
    user.nick_name = username
    user.password_hash = password
    user.address = address
    user.phone = phone
    try:
        db.session.add(user)
        db.session.commit()
        session["user_id"] = user.user_id
        session["nick_name"] = user.nick_name
        ret = {
            "errno": 0,
            "errmsg": "注册成功"
        }
        # return jsonify(ret)

    except Exception as ret:
        print("------>", ret)
        db.session.rollback()
        ret = {
            "errno": 1002,
            "errmsg": "注册失败"
        }
    return jsonify(ret)


@passport_blu.route("/passport/image_code")
def image_code():
    # 读取图片
    # with open("/static/index/images/yzm.png", "rb") as f:
    #     image = f.read()

    # 生成一张图片数据
    from utils.captcha.captcha import captcha

    # 生成验证码
    name, text, image = captcha.generate_captcha()

    print("刚刚生成的验证码:", text)

    # 返回响应内容
    resp = make_response(image)

    # 设置内容类型
    resp.headers["Content-Type"] = "image/png"

    return resp
